<template>
  <div class="content-div">
    <div ref="main" class="list-outbox" v-if="$route.query.type != '1'">
      <van-list :immediate-check="false" direction="up" v-model="loading" :finished="finished" @load="onLoad">
        <div :id="('msg' + index)" :class="{'msg-item-box-left' : item.type == '1' || item.type == '2', 'msg-item-box-right' : item.type == '3'}" v-for="(item, index) in list" :key="index">
          <div class="msg-content-box">
            <div class="msg-content">
              <img v-if="item.type == '1' || item.type == '2'" :src="item.userHeadSculpture" alt="" srcset="">
              <div>{{item.content}}</div>
              <img v-if="item.type == '3'" :src="item.accompanyingHeadSculpture" alt="" srcset="">
            </div>
            <div class="msg-time">{{item.createTime}}</div>
          </div>
        </div>
      </van-list>
    </div>
    <div ref="main" class="list-outbox" v-else>
      <van-list :immediate-check="false" direction="up" v-model="loading" :finished="finished" @load="onLoad">
        <div :id="('msg' + index)" :class="{'msg-item-box-left' : item.type == '1' || item.type === '2', 'msg-item-box-right' : item.type == '3'}" v-for="(item, index) in list" :key="index">
          <div class="msg-content-box">
            <div class="msg-content">
              <img v-if="item.type == '1' || item.type === '2'" src="@/assets/images/icon-msg.png" alt="" srcset="">
              <div>{{item.content}}</div>
              <img v-if="item.type == '3'" src="@/assets/images/icon-msg.png" alt="" srcset="">
            </div>
            <div class="msg-time">{{item.createTime}}</div>
          </div>
        </div>
      </van-list>
    </div>
    <div class="add-btn-box" v-if="$route.query.type != '1'">
      <van-field
        class="input-box"
        v-model="msgText"
        rows="1"
        :maxlength="100"
        @keydown.enter="sendMsg"
        @blur="blurIn()"
      />
      <div @click="sendMsg">
        <van-icon :color="(msgText ? '#1989fa' : '#666666')" name="share" />
      </div>
    </div>
  </div>
</template>

<script>
import { selectNotificationMessageList, updateIsReade } from '@/api/medical.js'
import { Toast } from 'vant'
export default {
  name: 'index',
  data () {
    return {
      text: '',
      tel: '',
      msgText: null,
      loading: false,
      finished: false,
      refreshing: false,
      list: [],
      pageParam: {
        pageNo: 1,
        pageSize: 20
      },
      // socket参数
      socket: null,
      timeout: 5000, // 15秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
      websocket: null
    }
  },
  computed: {
    accompanying_physician_id () {
      return this.$store.state.user.severUserInfo.accompanying_physician_id
    }
  },
  created () {},
  methods: {
    blurIn () {
      window.scrollTo(0, 0)
    },
    setNoRead () {
      updateIsReade({
        accompanying_physician_id: this.accompanying_physician_id,
        member_id: this.$store.state.user.token,
        userType: this.$route.query.type,
        wid: this.$route.query.wid
      }).then(res => {
        if (res.data.errcode === 0) {
          console.log(res)
        }
      })
    },
    onLoad (type) {
      selectNotificationMessageList({
        ...this.$route.query,
        accompanying_physician_id: this.accompanying_physician_id,
        ...this.pageParam
      }).then(res => {
        if (res.data.errcode === 0) {
          let list = []
          res.data.data.results.forEach(item => {
            list.unshift(item)
          })
          this.list = list.concat(this.list)
          this.loading = false
          this.$nextTick(() => {
            this.loading = false
            if (res.data.data.results.length <= 0 || res.data.data.results.length < this.pageParam.pageSize) {
              this.finished = true
            }
            if (type === 1) {
              this.toBottom()
            } else {
              let that = this
              this.$nextTick(() => {
                let main = that.$refs.main
                main.scrollTop = main.scrollHeight
              })
              // document.querySelector('.list-outbox').scrollTop = document.getElementById('msg19').offsetTop
            }
          })
          this.pageParam.pageNo += 1
        }
      })
    },
    isOpen (ws) {
      console.log(ws, 'wwww')
      return ws.readyState == ws.OPEN
    },
    sendMsg () {
      console.log('发送消息')
      if (this.isOpen(this.websocket)) {
        if (!this.msgText) {
          return false
        }
        this.msgText = this.msgText.replace(/\s+/g, '')
        let data = {
          accompanying_physician_id: this.$store.state.user.severUserInfo.accompanying_physician_id,
          content: this.msgText,
          have_no_read: this.$route.query.have_no_read,
          member_id: this.$route.query.member_id,
          type: '3',
          userType: '3',
          wid: this.$route.query.wid,
          accompanyingHeadSculpture: this.$store.state.user.severUserInfo.head_sculpture
        }
        console.log(data)
        this.websocket.send(JSON.stringify(data))
        this.list.push(data)
        this.msgText = ''
        // this.scrollToBottom()
        let that = this
        this.$nextTick(() => {
          let main = that.$refs.main
          main.scrollTop = main.scrollHeight
        })
      } else {
        Toast.fail('websocket连接已经关闭，请刷新页面尝试！')
      }
    },
    toBottom () {
      document.querySelector('.list-outbox').scrollTop = document.querySelector('.list-outbox').scrollHeight
    },
    // websocket实现聊天
    initWebSocket () {
      console.log('初始化')
      let that = this
      // ws等同于http，wss等同于https
      let wsUrl = `ws://accompaniment.lngov.top/api/websocket/?sid=${this.$store.state.user.severUserInfo.accompanying_physician_id}` // websocket链接地址
      try {
        if (window.WebSocket) {
          that.websocket = new WebSocket(wsUrl)
          that.websocket.onopen = that.websocketonopen
          that.websocket.onerror = that.websocketonerror
          that.websocket.onmessage = that.setOnmessageMessage
          that.websocket.onclose = that.websocketclose
        }
      } catch (e) {
        reset(wsUrl)
      }
    },
    websocketonopen () {
      // 开启心跳
      this.start()
    },
    start () {
      // 清除延时器
      console.log('WebSocket连接成功')
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        if (this.websocket && this.websocket.readyState == 1) {
          var data = { 'code': 1, 'msg': '心跳', 'data': '心跳' }
          this.websocket.send(JSON.stringify(data)) // 给服务端定时发送消息，保持链接
        } else {
          this.reconnect()
        }
        // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          this.websocket.close()
        }, this.timeout)
      }, this.timeout)
    },
    reset () { // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      // 重启心跳
      this.start()
    },
    // 重新连接
    reconnect () {
      console.log('重连')
      // this.pageParam.pageNo = 1
      // this.onLoad()
      if (this.lockReconnect) return
      this.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum)
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket()
        this.lockReconnect = false
      }, 2000)
    },
    // 监听消息(接收服务端返回的数据)
    setOnmessageMessage (event) {
      console.log(event, '服务器返回的数据')
      this.reset()
      // 自定义全局监听事件
      window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
          data: event.data
        }
      }))
      let message = JSON.parse(event.data)
      if (event.type === 'message' && message.type === '2') {
        // let data = {
        //   content: message,
        //   type: '2',
        //   accompanyingHeadSculpture: this.$route.query.accompanyingHeadSculpture
        // }
        // message['accompanyingHeadSculpture'] = this.$route.query.accompanyingHeadSculpture
        this.$forceUpdate()
        this.list.push(message)
        // this.toBottom()
        let that = this
        this.$nextTick(() => {
          let main = that.$refs.main
          main.scrollTop = main.scrollHeight
        })
      }
    },
    websocketonerror (e) {
      console.log('WebSocket连接发生错误' + e)
      this.reconnect()
    },
    websocketclose (e) {
      // this.websocket.close()
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      console.log('WebSocket连接关闭', this.lockReconnect)
      // websocket关闭后重新尝试连接,保持心跳
      // // setTimeout(() => {
      // if (this.lockReconnect) {
      //   console('关闭后重新连接')
      this.reconnect()
      // }
      // }, 5000)
    },
    websocketsend (messsage) {
      this.websocket.send(messsage)
    },
    closeWebSocket () { // 关闭websocket
      this.websocket.close()
    },
    btn () {
      console.log('fafdsaf')
      let that = this
      this.$nextTick(() => {
        let main = that.$refs.main
        main.scrollTop = '30'
      })
    }
  },
  destroyed () {
    if (this.websocket) {
      console.log('大发发')
      this.websocket.close()
      this.lockReconnect = true
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
    }
  },
  beforeDestroy () {
    if (this.websocket) {
      console.log('大发发111')
      this.websocket.close()
      this.websocket.close()
      this.lockReconnect = true
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
    }
  },
  mounted () {
    let that = this
    this.$nextTick(() => {
      let main = that.$refs.main
      main.scrollTop = main.scrollHeight
    })
    // this.$nextTick(() => {
    //   var parent = document.getElementById('parent')
    //   parent.scrollTop = '200'
    // })
    // this.scrollToBottom()
    console.log(this.$store.state.user.severUserInfo)
    this.pageParam.pageNo = 1
    this.onLoad(1)
    if (this.$route.query.have_no_read == '1') {
      this.setNoRead()
    }
    this.initWebSocket()
  }
}
</script>

<style scoped lang="less">
  .content-div{
    width: 100%;
    height: 100%;
    overflow-y: auto;
    padding-top: 10px;
    box-sizing: border-box;
    background-color: #F8F8F8;
    font-size: 12px;
    .list-outbox{
      padding-bottom: 60px;
      position: fixed;
      top: 0;
      bottom: 50px;
      width: 100%;
      overflow-y: auto;
      .msg-item-box-left, .msg-item-box-right{
        width: 300px;
        margin: 10px auto 30px;
        box-sizing: border-box;
        display: flex;
        flex-direction: row;
        .msg-content-box{
          width: 90%;
          .msg-content{
            display: flex;
            flex-direction: row;
            align-items: flex-start;
            width: 100%;
            margin-bottom: 10px;
            div{
              padding: 10px;
              border-radius: 6px;
              box-sizing: border-box;
              max-width: 100%;
              word-break: break-all;
            }
            img{
              width: 40px;
              height: 40px;
              border-radius: 4px;
            }
          }
          .msg-time{
            color: #999999;
          }
        }
      }
      .msg-item-box-left{
        justify-content: flex-start;
        .msg-content-box{
          text-align: left;
          .msg-content{
            justify-content: flex-start;
            div{
              background-color: #FFFFFF;
            }
            img{
              margin-right: 10px;
            }
          }
          .msg-time{
            padding-left: 50px;
          }
        }
      }
      .msg-item-box-right{
        justify-content: flex-end;
        .msg-content-box{
          text-align: right;
          .msg-content{
            justify-content: flex-end;
            div{
              background-color: #39b54a;
              color: #FFFFFF;
              text-align: left;
            }
            img{
              margin-left: 10px;
            }
          }
          .msg-time{
            padding-right: 50px;
          }
        }
      }
    }
    .add-btn-box{
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      min-height: 40px;
      box-sizing: border-box;
      padding: 10px;
      background-color: #FFFFFF;
      box-shadow: 0 0 10px 0 #CCCCCC;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      font-size: 26px;
      .input-box{
        border: 1px solid #CCCCCC;
        padding: 4px;
        width: calc(100% - 40px);
        font-size: 12px;
        border-radius: 6px;
      }
      .input-box:focus {
        outline: none;
      }
      div{
        width: 40px;
        text-align: right;
        box-sizing: border-box;
      }
    }
  }
</style>
